package util

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"io"
	"net/http"
	url2 "net/url"
)

type  SentenceInfo struct {
	ExampleSentence string  //例句
	ExampleExplain string  //解释
}
type WordInfo struct {
	Word string
	Type []string // 动词，名称形容词等
	Explain[] string
	SentenceExample [] SentenceInfo

	US string  //英语音标
	UK string //美式音标

}
func ParseHtml(r  io.Reader,size int)(*WordInfo,error) {
	doc, err := goquery.NewDocumentFromReader(r)
	if err!=nil {
		return nil,nil
	}
	word := &WordInfo{}
	//单词
	word.Word = doc.Find("#bpage.b_drk .qdef .hd_div strong, #bpage.b_med .qdef .hd_div strong, .qdef .hd_div strong ").First().Text()
	//类型
	doc.Find("body > div.contentPadding > div > div > div.lf_area > div.qdef > ul > li").Each(func(i int, li *goquery.Selection) {
		first := li.Find(".pos").First().Text()
		ch := li.Find(".def span").First().Text()
		word.Type = append(word.Type, first+" "+ch)
	})
	doc.Find("#pos_0 > div:nth-child(1) > table > tbody > tr > td").Each(func(i int, td *goquery.Selection) {
		sentence := td.Text()
		word.Explain = append(word.Explain,sentence)
	})
	if size <= 0 {
		size= 3
	}
	 doc.Find("#sentenceSeg .se_li").
		EachWithBreak(func(i int, selection *goquery.Selection) bool {
		zh := selection.Find(".sen_cn").Text()
		en := selection.Find(".sen_en").Text()
		word.SentenceExample = append(word.SentenceExample,SentenceInfo{
			ExampleSentence: en,
			ExampleExplain: zh,
		})
		return len(word.SentenceExample)< size
	})
	return word,nil

}

func ParseWord(word string,limit int)(*WordInfo,error) {

	var url string = fmt.Sprintf("http://cn.bing.com/dict/search?q=%v&", url2.QueryEscape(word))
	fmt.Printf("res := %v\n",url)
	//fmt.Printf(url)
	resp, err := http.Get(url)
	if err !=nil {
		fmt.Printf("errInfo := %v\n",err)
		return nil,nil
	}
	defer resp.Body.Close()
	//fmt.Println(resp.Body)‘
	return ParseHtml(resp.Body,limit)
	//body,err := ioutil.ReadAll(resp.Body)
	//fmt.Println(string(body))
	//if resp.StatusCode == 200 {
	//	fmt.Println("OK");
	//}
	//return
}



